package com.tanguy.user.utlis.extend

import android.content.res.Resources
import android.support.design.widget.TabLayout
import android.util.TypedValue
import android.widget.LinearLayout
import java.lang.reflect.Field

/**
 * Created by dab on 2017/10/23 0023 11:54
 */
fun TabLayout.setIndicator(leftDip: Int, rightDip: Int) {
    val tabLayout = this.javaClass
    var tabStrip: Field? = null
    try {
        tabStrip = tabLayout.getDeclaredField("mTabStrip")
    } catch (e: NoSuchFieldException) {
        e.printStackTrace()
        return
    }

    tabStrip!!.isAccessible = true
    var llTab: LinearLayout? = null
    try {
        llTab = tabStrip.get(this) as LinearLayout
    } catch (e: IllegalAccessException) {
        e.printStackTrace()
        return
    }

    val left = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip.toFloat(), Resources.getSystem().displayMetrics).toInt()
    val right = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip.toFloat(), Resources.getSystem().displayMetrics).toInt()

    for (i in 0..llTab.childCount - 1) {
        val child = llTab.getChildAt(i)
        child.setPadding(0, 0, 0, 0)
        val params = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1f)
        params.leftMargin = left
        params.rightMargin = right
        child.layoutParams = params
        child.invalidate()
    }
}